package com.powerbosframework.web.action;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.powerbosframework.beans.entity.ViewEntity;

/**
 * 请求动作分发器
 * @author youfu.wang
 * @version 1.0
 */
public class ActionDispatcher {
	private HttpServletRequest httpRequest;
	private HttpServletResponse httpResponse;

	
	public ActionDispatcher(HttpServletRequest httpRequest,HttpServletResponse httpResponse){
		this.httpRequest=httpRequest;
		this.httpResponse=httpResponse;		
	}	
	/**
	 * 分发视图
	 * @param mappingEntity
	 * @throws ServletException 
	 * @throws IOException 
	 */
	public void dispatcher(String path,ViewEntity viewEntity) throws IOException, ServletException{		
		if(viewEntity==null){
			String msg="The requested resource "+path+" is not available";
			this.doDispatcherError(404,msg);  	   
			return;
		}		
		String s=viewEntity.getValue();
		String s1=null;
    	if(s.startsWith("/")){
    		s1 =s;
    	}else
    		s1="/"+s;    	
    	doDispatcher(s1);
	}
	public static String redirectURL(String s){
		if(s==null){
			return s;
		}		
		if(s.startsWith("/")){		
			int i=s.lastIndexOf("/");
			int j=s.lastIndexOf(".");		
		    if(j!=0&j>i){
		    	s=s.substring(1, j);		    	
		    }
		}else{
			int i=s.lastIndexOf(".");
			if(i>0){
				s=s.substring(0, i);
			}			
		}			
		return s;
	}
	/**
     * 执行分发
     * @param s
     * @param httpservletrequest
     * @param httpservletresponse
     * @throws IOException
     * @throws ServletException
     */
    private void doDispatcher(String s) throws IOException, ServletException{
    	RequestDispatcher requestdispatcher = httpRequest.getRequestDispatcher(s);
        if(requestdispatcher == null){
        	this.doDispatcherError(500,s);          
        	return;
        } else{
            requestdispatcher.forward(httpRequest, httpResponse);
            return;
        }
    }
    public void doDispatcherError(int sc,String msg) throws IOException{    	
		httpResponse.sendError(sc,msg);   		
    }
}
